/// @tags: TreeHash
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

namespace BlueQuantum {

typedef long long LL;

int const N = 1e3 + 5;

LL ans[N][N], n, m, heads[N], to[N], nxt[N], ecnt;

inline void add(int x, int y) {
  to[++ecnt] = y;
  nxt[ecnt] = heads[x];
  heads[x] = ecnt;
}

LL getHash(int x, int f) {
  LL q[N], ans = N, top = 0;
  for (int i = heads[x]; i; i = nxt[i])
    if (to[i] != f) q[++top] = getHash(to[i], x);
  sort(q + 1, q + top + 1);
  for (int i = 1; i <= top; ++i) ans = ans * 2333 + q[i];
  return ans * 2333 + N + 1;
}

inline int main() {
  cin >> m;
  for (int i = 1; i <= m; ++i) {
    ecnt = 0;
    memset(heads, 0, sizeof(heads));
    cin >> n;
    for (int j = 1, x; j <= n; ++j) {
      cin >> x;
      if (x != 0) add(x, j), add(j, x);
    }
    for (int j = 1; j <= n; ++j) ans[i][j] = getHash(j, 0);
    sort(ans[i] + 1, ans[i] + n + 1);
    for (int j = 1, k = 0; j <= i; ++j, k = 0) {
      while (k <= n) {
        ++k;
        if (ans[i][k] != ans[j][k]) break;
      }
      if (k > n) {
        cout << j << '\n';
        break;
      }
    }
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("TreeHash.in", "r", stdin);
  freopen("TreeHash.out", "w", stdout);
#endif
#endif

  ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
